import 'dart:ui';

import 'package:carousel_slider/carousel_options.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:onlineshop/constants/my_color.dart';

class DetailPage extends StatefulWidget {
  const DetailPage({super.key});

  @override
  State<DetailPage> createState() => _DetailPageState();
}

class _DetailPageState extends State<DetailPage> {
  // 图片数据
  final imgList = [
    {'imgPath': 'assets/images/detail/swiper-bag.png', 'id': '1'},
    {'imgPath': 'assets/images/detail/swiper-bag.png', 'id': '2'},
    {'imgPath': 'assets/images/detail/swiper-bag.png', 'id': '3'}
  ];

// 当前swiper索引
  int currentSwiper = 1;

// 改变swiper
  void changeSwiper(id) {
    setState(() {
      currentSwiper = int.parse(id);
    });
  }

// 尺寸数据
  final sizeList = [
    {'size': 'S', 'id': '1'},
    {'size': 'M', 'id': '2'},
    {'size': 'L', 'id': '3'},
    {'size': 'XL', 'id': '4'},
  ];

  // 当前选中的尺寸
  int currentSize = 1;

  // 选择尺寸
  void changeSize(id) {
    setState(() {
      currentSize = id;
    });
  }

  // 颜色数据
  final colorList = [
    {'color': '0xffF24835', 'id': '1'},
    {'color': '0xffE17A64', 'id': '2'},
    {'color': '0xffFFEABD', 'id': '3'},
    {'color': '0xff725EE0', 'id': '4'},
  ];

  // 当前选中的颜色
  int currentColor = 1;

  // 选择颜色
  void changeColor(id) {
    setState(() {
      currentColor = id;
    });
  }

  // 数量
  int currentCount = 1;

  // 数量加
  void addCount() {
    setState(() {
      currentCount++;
    });
  }

  // 数量减
  void reduceCount() {
    setState(() {
      if (currentCount <= 1) return;
      currentCount--;
    });
  }

  // 添加到购物车
  void addToCart() {
    print('添加到购物车');
    Navigator.pushNamed(context, '/cart');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: GestureDetector(
          onTap: () => Navigator.pop(context),
          child: const Padding(
            padding: EdgeInsets.only(left: 16),
            child: Icon(Icons.arrow_back),
          ),
        ),
        actions: [
          Row(
            children: [
              IconButton(
                onPressed: () {
                  Navigator.pushNamed(context, '/cart');
                },
                icon: Image.asset('assets/icons/cart.png'),
              ),
            ],
          ),
        ],
        backgroundColor: const Color(MyColor.BACKGROUND_COLOR),
      ),
      backgroundColor: const Color(MyColor.BACKGROUND_COLOR),
      body: Column(
        children: [
          // swiper
          MySwiper(imgList, changeSwiper),

          const SizedBox(
            height: 20,
          ),

          // 指示器
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: imgList
                .map((item) => Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 5),
                      child: Container(
                        width: 8,
                        height: 8,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: const Color(MyColor.PRIMARY_COLOR).withOpacity(
                              currentSwiper == int.parse(item['id']!)
                                  ? 1
                                  : 0.2),
                        ),
                      ),
                    ))
                .toList(),
          ),

          const SizedBox(
            height: 20,
          ),

          // 详细信息
          Expanded(
            child: Container(
              width: double.infinity,
              padding: const EdgeInsets.only(
                top: 35,
                left: 24,
                right: 24,
              ),
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(30),
                  topRight: Radius.circular(30),
                ),
              ),
              child: Column(
                children: [
                  // 名字
                  const Row(
                    children: [
                      Text(
                        "手提包皮夹",
                        style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.w700,
                            color: Color(MyColor.PRIMARY_COLOR)),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  // 价格
                  const Row(
                    children: [
                      Text(
                        '¥ 120',
                        style: TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.w700,
                          color: Color(0xffF83A26),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(
                    height: 5,
                  ),
                  // 介绍
                  const Text(
                    "钱包一词最初指的是用来装硬币的小袋子，在英语国家，它仍然被用来指代一个小钱袋，手提包是一个较大的配件，用来装物品。",
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                      color: Color(MyColor.PRIMARY_COLOR),
                    ),
                  ),

                  const SizedBox(
                    height: 5,
                  ),

                  // 尺寸选择
                  SizeSelector(sizeList, currentSize, changeSize),

                  const SizedBox(
                    height: 5,
                  ),

                  // 颜色数量
                  SizedBox(
                    width: double.infinity,
                    child: Row(
                      // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        ColorSelector(colorList, currentColor, changeColor),
                        const Expanded(
                          child: Text(''),
                        ),
                        Counter(
                          currentCount,
                          reduceCount,
                          addCount,
                        ),
                      ],
                    ),
                  ),

                  const Expanded(child: Text('')),
                  // 添加购物车按钮
                  AdjustCartButton(addToCart),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

//  swiper
Widget MySwiper(
  List imgList,
  Function changeSwiper,
) {
  return CarouselSlider(
    items: imgList
        .map((item) => Container(
              child: Image.asset(item['imgPath']),
            ))
        .toList(),
    options: CarouselOptions(
      height: 246.0,
      autoPlay: false,
      enlargeCenterPage: true,
      // aspectRatio: 16 / 9,
      autoPlayCurve: Curves.easeInOut,
      autoPlayAnimationDuration: const Duration(milliseconds: 800),
      viewportFraction: 0.8,
      onPageChanged: (index, reason) => changeSwiper(imgList[index]['id']),
    ),
  );
}

// 尺寸选择器
Widget SizeSelector(
  List sizeList,
  int currentSize,
  Function changeSize,
) {
  return Row(
    children: sizeList
        .map(
          (item) => GestureDetector(
            onTap: () {
              changeSize(int.parse(item['id']));
            },
            child: Padding(
              padding: EdgeInsets.only(
                left: item['id'] == '1' ? 1 : 8,
                right: 8,
              ),
              child: Container(
                width: 45,
                height: 45,
                decoration: BoxDecoration(
                  color: currentSize == int.parse(item['id']!)
                      ? const Color(MyColor.PRIMARY_COLOR)
                      : const Color(MyColor.BACKGROUND_COLOR),
                  borderRadius: BorderRadius.circular(13),
                ),
                child: Center(
                  child: Text(
                    item['size']!,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w400,
                      color: currentSize == int.parse(item['id']!)
                          ? Colors.white
                          : const Color(MyColor.PRIMARY_COLOR),
                    ),
                  ),
                ),
              ),
            ),
          ),
        )
        .toList(),
  );
}

// 颜色选择器
Widget ColorSelector(List colorList, int currentColor, Function changeColor) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      const Text(
        '颜色',
        textAlign: TextAlign.start,
        style: TextStyle(
          fontSize: 15,
          fontWeight: FontWeight.w700,
        ),
      ),
      const SizedBox(
        height: 10,
      ),
      Row(
        children: colorList
            .map(
              (item) => Padding(
                padding: const EdgeInsets.only(
                  right: 7,
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Align(
                      child: Container(
                        width: 22,
                        height: 22,
                        decoration: BoxDecoration(
                          border: currentColor == int.parse(item['id']!)
                              ? Border.all(
                                  width: 1,
                                  color: Color(int.parse(item['color']!)),
                                )
                              : const Border(),
                          shape: BoxShape.circle,
                        ),
                      ),
                    ),
                    Align(
                      alignment: Alignment.center,
                      child: GestureDetector(
                        onTap: () {
                          changeColor(
                            int.parse(item['id']!),
                          );
                        },
                        child: Container(
                          width: 16,
                          height: 16,
                          decoration: BoxDecoration(
                            color: Color(int.parse(item['color']!)),
                            shape: BoxShape.circle,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )
            .toList(),
      ),
    ],
  );
}

// 数量选择器
Widget Counter(
  int currentCount,
  Function reduceCount,
  Function addCount,
) {
  return Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      const Text(
        '数量',
        textAlign: TextAlign.start,
        style: TextStyle(
          fontSize: 15,
          fontWeight: FontWeight.w700,
        ),
      ),
      const SizedBox(
        height: 10,
      ),
      Row(
        children: [
          GestureDetector(
            onTap: () {
              reduceCount();
            },
            child: Container(
              width: 25,
              height: 25,
              decoration: BoxDecoration(
                color: const Color(MyColor.PRIMARY_COLOR),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(
                Icons.remove,
                color: Colors.white,
                size: 18,
              ),
            ),
          ),
          const SizedBox(
            width: 12,
          ),
          Text(
            '$currentCount',
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w400,
            ),
          ),
          const SizedBox(
            width: 12,
          ),
          GestureDetector(
            onTap: () {
              addCount();
            },
            child: Container(
              width: 25,
              height: 25,
              decoration: BoxDecoration(
                color: const Color(0xffF83A26),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Icon(
                Icons.add,
                color: Colors.white,
                size: 18,
              ),
            ),
          ),
        ],
      )
    ],
  );
}

// 调价购物车按钮
Widget AdjustCartButton(
  Function addToCart,
) {
  return Padding(
    padding: const EdgeInsets.only(bottom: 25),
    child: SizedBox(
      width: double.infinity,
      height: 83,
      child: ElevatedButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(
            const Color(MyColor.PRIMARY_COLOR),
          ),
          shape: MaterialStateProperty.all(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(30.0), // 设置圆角半径
            ),
          ),
        ),
        onPressed: () {
          addToCart();
        },
        child: const Text(
          '添加到购物车',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w400,
            color: Color(0xffFFDB8B),
          ),
        ),
      ),
    ),
  );
}
